<template>
<div>
  <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <el-card>
    <el-row :gutter="20">
  <el-col :span="8">
    <el-input placeholder="请输入要搜索的用户名" v-model="userinfo.query" clearable @clear="getUserList" >
      <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
  </el-input>
  </el-col>
  <el-col :span="6"><el-button type="success" @click="dialogVisible = true">添加用户</el-button></el-col>
    </el-row>
     <el-table
      :data="userlist"
      style="width: 100%" border stripe>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="username" label="用户" > </el-table-column>
      <el-table-column prop="email" label="邮箱" > </el-table-column>
      <el-table-column prop="mobile" label="电话" > </el-table-column>
      <el-table-column prop="role_name" label="角色" > </el-table-column>
      <el-table-column  label="状态" >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state" active-color="#13ce66" @change="changestate(scope.row)">
          </el-switch>
        </template>
         </el-table-column>
      <el-table-column  label="操作" >
        <template slot-scope="scope">
        <el-button type="primary" icon="el-icon-edit"  size="mini" @click="changeuser(scope.row)"></el-button>
        
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="remove(scope.row.id)"></el-button>
        <el-tooltip  effect="dark" content="用户设置" placement="top" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
          </el-tooltip>
          </template>
         </el-table-column>
      
    </el-table>
     <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="userinfo.pagenum"
      :page-sizes="[2, 3, 4, 6]"
      :page-size="userinfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </el-card>
  <!-- 增加用户的对话框 -->
  <el-dialog
  title="添加用户"
  :visible.sync="dialogVisible"
  width="40%"
  :before-close="handleClose" @close="resetaddruleForm">
 <el-form :model="addruleForm" :rules="addrules" ref="addruleForm" label-width="100px" >
  <el-form-item label="用户名称" prop="username">
    <el-input v-model="addruleForm.username"></el-input>
  </el-form-item>
  <el-form-item label="用户密码" prop="password">
    <el-input v-model="addruleForm.password"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addruleForm.email"></el-input>
  </el-form-item>
  <el-form-item label="手机" prop="mobile">
    <el-input v-model="addruleForm.mobile"></el-input>
  </el-form-item>
 </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<!-- 修改用户的对话框 -->
<el-dialog
  title="修改用户"
  :visible.sync="changedialogVisible"
  width="30%"
  :before-close="handleClose">
  <el-form :model="idForm" :rules="idrules" ref="idruleForm" label-width="100px" >
  <el-form-item label="用户名称" prop="username" >
    <el-input v-model="idForm.username" disabled></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="idForm.email"></el-input>
  </el-form-item>
  <el-form-item label="手机" prop="mobile">
    <el-input v-model="idForm.mobile"></el-input>
  </el-form-item>
 </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="changedialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUser">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>

<script>
export default {
  data(){
    var checkEmail = (rule, value, callback) => {
      const cemail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if (cemail.test(value)) {
          return callback();
        }
        callback(new Error('这不是合法邮箱'))

    }
    var checkMobile = (rule, value, callback) => {
      const cmobile = /^(((13[0-9])|(14[5-7])|(15[0-9])|(17[0-9])|(18[0-9]))+\d{8})$/ ;
        if (cmobile.test(value)) {
          return callback();
        }
        callback(new Error('这不是合法手机号'))
    }
    return{
      userinfo:{
            query:'',
            pagenum:1,
            pagesize:4
          },
      userlist:[],
      total:0,
      dialogVisible:false,
      changedialogVisible:false,
      addruleForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      idForm:{
        
      },
      addrules:{
        username:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15个字符', trigger: 'blur' }
        ],
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {validator:checkEmail,trigger: 'blur' }
            
        ],
        mobile:[
          { required: true, message: '请输入手机号码', trigger: 'blur' },
           {validator:checkMobile,trigger: 'blur' }
        ]
      },
      idrules:{
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {validator:checkEmail,trigger: 'blur' }
        ],
        mobile:[
             { required: true, message: '请输入手机号码', trigger: 'blur' },
           {validator:checkMobile,trigger: 'blur' }
        ]
        
      }
    }
    

  },
  created(){
    this.getUserList()
  },
  methods:{
    async getUserList(){
      const {data:res}= await this.$http.get('users',{params:this.userinfo})
      if(res.meta.status!==200){
        return this.$message.error('获取数据失败')
      }
      this.userlist=res.data.users
      this.total=res.data.total
      console.log(this.userlist)
    },
    //监听pagesize事件
    handleSizeChange(newsize){
        console.log(newsize)
        this.userinfo.pagesize=newsize
        this.getUserList()
    },
    //监听页码值改变
    handleCurrentChange(newpage){
        console.log(newpage)
        this.userinfo.pagenum=newpage
        this.getUserList()
    },
    async changestate(userinfo){
      console.log(userinfo)
      const {data:res} =await this.$http.put(`/users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status!==200){
        userinfo.mg_state=!userinfo.mg_state
        return this.$message.error('跟新用户失败！')
      }
      this.$message.success('跟新状态成功')
    },
    resetaddruleForm(){
      this.$refs.addruleForm.resetFields()
    },
    addUser(){
      this.$refs.addruleForm.validate(async valid=>{
        if(!valid) return
        const {data:res} = await this.$http.post('users',this.addruleForm)
        
        if(res.meta.status!==201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
      
    },
    changeuser(info){
      this.changedialogVisible=true
      // console.log(info)
      
      this.idForm=info
    },
    async editUser(){
        this.$refs.idruleForm.validate(async valid=>{
        if(!valid) return
        const {data:res} = await this.$http.put('users/'+this.idForm.id,{
          id:this.idForm.id,
         email: this.idForm.email,mobile:this.idForm.mobile
        })
        
        if(res.meta.status!==200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.changedialogVisible = false
        this.getUserList()
      })
        
        // const {data:res}=await this.$http.put('users/'+this.idForm.id,{
        //   id:this.idForm.id,
        //  email: this.idForm.email,mobile:this.idForm.mobile
        // })
        
        // // if(res.meta.status!==200){
        // //   return this.$message.error('修改失败')
        // // }
        // //删除对话框
        // this.changedialogVisible=false
        // //跟新列表
        
        // //弹出成功
        // this.$message.success('修改成功')
        // this.getUserList()
      
    },
    async remove(id){
       this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          const {data:res}= this.$http.delete('users/'+id)
           
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        this.getUserList()
    }
  }

}
</script>

<style lang="less" scoped>

</style>
